﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
using Infrastructure;
using Login.Events;
using Login.Views;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.Regions;
using NetDisk.Service;
using File = Model.File;
using MessageBox = System.Windows.MessageBox;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;

namespace Login.ViewModels
{
    [Export]
    public class MenuViewModel : BindableBase
    {
        private  File File = new File();
        public ICommand ManipulateStaff { get; }
        private IRegionManager _regionManager;
        private IEventAggregator _eventAggregator;
        public ICommand ImgCommand { get; }
        private  IDataService _dataService;
        public ICommand UploadCommand { get; }
        public ICommand DownLoadCommand { get; }
        public ICommand DeleteCommand { get; }
        

        private int _value1;

        public int Value1
        {
            get { return _value1;}
            set { SetProperty(ref _value1, value); }
        }
        
        string _filename = string.Empty;

        [ImportingConstructor]
        public MenuViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IDataService dataService)
        {
           
            _dataService = dataService;
              _regionManager = regionManager;
            _eventAggregator = eventAggregator;
            ManipulateStaff = new DelegateCommand<object>(ExecuteManipStaff);
            ImgCommand = new DelegateCommand<object>(ExecuteImgCommadn);
            UploadCommand = new DelegateCommand<object>(ExecuteUploadCommand);
            DownLoadCommand = new DelegateCommand<object>(ExecuteDownLoadCommand);
            DeleteCommand = new DelegateCommand<object>(ExecuteDeleteCommand);
            _eventAggregator.GetEvent<DownLoad>().Subscribe(OnDownLoad);
            Value1 = 20;
        }

        private async void ExecuteDeleteCommand(object o)
        {
            if (System.IO.File.Exists(File.FileFullName))
            {
                await Task.Run((() =>
                {
                    System.IO.File.Delete(File.FileFullName);
                }));
                _eventAggregator.GetEvent<Refresh>().Publish(1);
                MessageBox.Show("已删除文件" + File.FileName);
            }
        }
        
        private void OnDownLoad(Item item)
        {
            File.FileFullName = item.FileFullName;
            File.FileName = item.FileName;
        }
        private void ExecuteManipStaff(object o)
        {
        }
        private void ExecuteImgCommadn(object o)
        {
        }
        private   void ExecuteDownLoadCommand(object o)
        {
            FolderBrowserDialog dilog = new FolderBrowserDialog {Description = "请选择文件夹"};
            if (dilog.ShowDialog() == DialogResult.OK)
            {
                string path = File.FileFullName;
                var webClient = new WebClient();
                var dlg = new SaveFileDialog
                {
                    FileName = File.FileName,
                    InitialDirectory = dilog.SelectedPath
                };
                var filename = dlg.InitialDirectory+"\\"+ dlg.FileName;
           
                    try
                    {
                        webClient.DownloadFile(path, filename);
                        MessageBox.Show("文件下载成功！");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("文件下载失败，请稍后重试！");
                    }

            }  
        }
        private  void ExecuteUploadCommand(object o)
        {
            var dlg = new Microsoft.Win32.OpenFileDialog();
            var myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;
            dlg.Filter = "图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg;*.zip;*.txt;*.docx";
     
            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                _filename = dlg.FileName;
                WebRequest request = WebRequest.Create(_filename);
                WebResponse respone = request.GetResponse();
                var contentLength = respone.ContentLength;
                Stream netStream = respone.GetResponseStream();
                Stream fileStream = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                byte[] read = new byte[1024];
                int realReadLen = netStream.Read(read, 0, read.Length);
   
                while (realReadLen > 0)
                {
                    realReadLen = netStream.Read(read, 0, read.Length);
                    _eventAggregator.GetEvent<Process>().Publish((int) contentLength);

                }
                netStream.Close();
                fileStream.Close();
                    try
                    {
                            myWebClient.UploadFile(new Uri(_dataService.HostUrl + dlg.SafeFileName), "PUT", _filename);
                        _eventAggregator.GetEvent<Refresh>().Publish(1);
                        MessageBox.Show("文件上传成功！");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("文件上传失败，请稍后重试！");
                    }
            }
        }
        
    }
}
